package io.github.jsp.controller;


import io.github.jsp.model.Task;
import io.github.jsp.model.TaskExecution;
import io.github.jsp.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/tasks")
public class TaskController {

    private final TaskService taskService;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    public TaskController(TaskService taskService) {
        this.taskService = taskService;
    }

    @GetMapping
    public ResponseEntity<List<Task>> getAllTasks() {
        return ResponseEntity.ok(taskService.findAllEnabledTasks());
    }

    @GetMapping("/{id}")
    public ResponseEntity<Task> getTaskById(@PathVariable int id) {
        Task task = taskService.findTaskById(id);
        if (task == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(task);
    }

    @PostMapping
    public ResponseEntity<String> addTask(@RequestBody Task task) {
        boolean success = taskService.addTask(task);
        if (success) {
            return ResponseEntity.ok("Task added successfully");
        } else {
            return ResponseEntity.internalServerError().body("Failed to add task");
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<String> updateTask(@PathVariable int id, @RequestBody Task task) {
        task.setId(id);
        boolean success = taskService.updateTask(task);
        if (success) {
            return ResponseEntity.ok("Task updated successfully");
        } else {
            return ResponseEntity.internalServerError().body("Failed to update task");
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteTask(@PathVariable int id) {
        boolean success = taskService.deleteTask(id);
        if (success) {
            return ResponseEntity.ok("Task deleted successfully");
        } else {
            return ResponseEntity.internalServerError().body("Failed to delete task");
        }
    }

    @PostMapping("/{id}/status")
    public ResponseEntity<String> toggleTaskStatus(@PathVariable int id, @RequestBody Map<String, String> statusMap) {
        String status = statusMap.get("status");
        if (status == null || status.isEmpty()) {
            return ResponseEntity.badRequest().body("Status is required");
        }
        
        boolean success = taskService.toggleTaskStatus(id, status);
        if (success) {
            return ResponseEntity.ok("Task status updated successfully");
        } else {
            return ResponseEntity.internalServerError().body("Failed to update task status");
        }
    }

    @PostMapping("/{id}/execute")
    public ResponseEntity<String> executeTaskNow(@PathVariable int id) {
        boolean success = taskService.executeTaskNow(id);
        if (success) {
            return ResponseEntity.ok("Task execution triggered");
        } else {
            return ResponseEntity.internalServerError().body("Failed to trigger task execution");
        }
    }

    @GetMapping("/{id}/history")
    public ResponseEntity<List<TaskExecution>> getTaskExecutionHistory(@PathVariable int id) {
        return ResponseEntity.ok(taskService.getTaskExecutionHistory(id));
    }

    @GetMapping("/next-run-time")
    public ResponseEntity<String> getNextRunTime(@RequestParam String cronExpression) {
        Date nextRunTime = taskService.getNextRunTime(cronExpression);
        if (nextRunTime == null) {
            return ResponseEntity.badRequest().body("Invalid cron expression");
        }
        return ResponseEntity.ok(dateFormat.format(nextRunTime));
    }
}